package com.pri.chat.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.business.session.viewholder.GlideBlurTransformation;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.MeGiftBean;
import com.netease.nim.uikit.net.entity.OtherMsgBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.MainActivity;
import com.pri.chat.R;
import com.pri.chat.adapter.GiftMeAdapter;
import com.pri.chat.adapter.OtherInfoImgAdapter;
import com.pri.chat.model.GzModel;
import com.pri.chat.model.OtherModel;
import com.pri.chat.model.SayModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.FlowLayout;
import com.pri.chat.utils.GlideEngine;
import com.pri.chat.utils.StringUtils;
import com.pri.chat.utils.statusbar.StatusBarUtil;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/8
 */
public class OtherPeopleMsgActivity extends AppCompatActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.sex_bg)
    View sex_bg;
    @BindView(R.id.tv_dt_age)
    TextView tv_dt_age;
    @BindView(R.id.sex_logo)
    ImageView sex_logo;
    @BindView(R.id.rl_logo)
    LinearLayout rlLogo;

    @BindView(R.id.vip_bg)
    TextView vip_bg;
    @BindView(R.id.vip_super_bg)
    TextView vip_super_bg;
    @BindView(R.id.fensi_bg)
    TextView fensi_bg;


    @BindView(R.id.tv_me_name)
    TextView tvMeName;
    @BindView(R.id.tv_wish_money)
    TextView tvWishMoney;
    @BindView(R.id.rv_dt)
    RecyclerView rvDt;
    @BindView(R.id.rv_liwu)
    RecyclerView rv_liwu;
    @BindView(R.id.rv_wish)
    RecyclerView rvWish;
    @BindView(R.id.tv_real_verify)
    ImageView tvRealVerify;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_heart_msg)
    TextView tvHeartMsg;
    @BindView(R.id.tv_say_hello)
    TextView tvSayHello;
//    @BindView(R.id.tv_send_message)
//    TextView tvSendMessage;
    @BindView(R.id.gz_linear)
    View gz_linear;
    @BindView(R.id.gz_image)
    ImageView gz_image;
    @BindView(R.id.tv_coll_other)
    TextView tvCollOther;
    @BindView(R.id.tv_fast)
    TextView tvFast;
    @BindView(R.id.iv_bg)
    ImageView ivBg;

    @BindView(R.id.dtRelation)
    View dtRelation;
    @BindView(R.id.wishRelation)
    View wishRelation;

    @BindView(R.id.baseInfo)
    FlowLayout baseInfo;

    @BindView(R.id.noData)
    TextView noData;

    private OtherMsgBean otherMsgBean;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_people_msg_layout);
        StatusBarUtil.setStatusBar(this,true,0,false,true);
        ButterKnife.bind(this);
        initView();
    }

    private String mOtherMemberId;

    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        mOtherMemberId = bundle.getString("id");
        initDT();
        initLiWu();
        initWish();

    }

    private List<String> mWishImgList;
    private OtherInfoImgAdapter mWishImgAdapter;

    private void initWish() {
        mWishImgList = new ArrayList<>();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        rvWish.setLayoutManager(gridLayoutManager);
        mWishImgAdapter = new OtherInfoImgAdapter(R.layout.item_other_info_img, mWishImgList);
        rvWish.setAdapter(mWishImgAdapter);
        mWishImgAdapter.setOnItemClickListener((adapter, view, position) -> {
//            PictureSelector.create(this)
//                    .themeStyle(R.style.picture_default_style)
//                    .isNotPreviewDownload(true)
//                    .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
//                    .openExternalPreview(position, wishMediaList);
            Bundle bundle = new Bundle();
            bundle.putString("id", mOtherMemberId);
            bundle.putString("name",otherMsgBean.getMemberInfo().getNcName());
            bundle.putInt("canJiaSu",otherMsgBean.getCanJiaSu());
            RxActivityTool.skipActivity(this, OtherWishActivity.class, bundle);
        });
    }

    private List<String> mDtImgList;
    private OtherInfoImgAdapter mDTImgAdapter;

    private void initDT() {
        mDtImgList = new ArrayList<>();

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        rvDt.setLayoutManager(gridLayoutManager);
        mDTImgAdapter = new OtherInfoImgAdapter(R.layout.item_other_info_img, mDtImgList);
        rvDt.setAdapter(mDTImgAdapter);
        mDTImgAdapter.setOnItemClickListener((adapter, view, position) -> {
//            PictureSelector.create(this)
//                    .themeStyle(R.style.picture_default_style)
//                    .isNotPreviewDownload(true)
//                    .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
//                    .openExternalPreview(position, dtMediaList);
            Bundle bundle = new Bundle();
            bundle.putString("id", mOtherMemberId);
            bundle.putString("name",otherMsgBean.getMemberInfo().getNcName());
            RxActivityTool.skipActivity(this, DongTaiAndVideoActivity.class, bundle);
        });
    }

    private List<MeGiftBean> mLwList;
    private GiftMeAdapter mLiWuAdapter;
    private void initLiWu() {
        mLwList = new ArrayList<>();
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 4);
        rv_liwu.setLayoutManager(linearLayoutManager);
        rv_liwu.setNestedScrollingEnabled(false);
        mLiWuAdapter = new GiftMeAdapter(R.layout.item_gift_me, mLwList);
        rv_liwu.setAdapter(mLiWuAdapter);
    }

    List<LocalMedia> dtMediaList = new ArrayList<>();
    List<LocalMedia> wishMediaList = new ArrayList<>();
    private List<String> infoList = new ArrayList<>();
    protected void initData() {
        SubscriberOnNextListener<BaseBean<OtherMsgBean>> onNextListener = baseBean -> {
            otherMsgBean = baseBean.getData();
            infoList.clear();

            infoList.add("性别 "+otherMsgBean.getMemberInfo().getSex());
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getAge())){
                infoList.add("年龄 "+otherMsgBean.getMemberInfo().getAge());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getShengao())){
                infoList.add("身高 "+otherMsgBean.getMemberInfo().getShengao());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getTizhong())){
                infoList.add("体重 "+otherMsgBean.getMemberInfo().getTizhong());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getCity())){
                infoList.add("城市 "+otherMsgBean.getMemberInfo().getCity());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getXingzuo())){
                infoList.add("星座 "+otherMsgBean.getMemberInfo().getXingzuo());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getXueli())){
                infoList.add("学历 "+otherMsgBean.getMemberInfo().getXueli());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getZhiye())){
                infoList.add("职业 "+otherMsgBean.getMemberInfo().getZhiye());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getSfjsyuehui())){
                infoList.add("可否约会 "+otherMsgBean.getMemberInfo().getSfjsyuehui());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getTixing())){
                infoList.add("体型 "+otherMsgBean.getMemberInfo().getTixing());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getQinggan())){
                infoList.add("情感状态 "+otherMsgBean.getMemberInfo().getQinggan());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getSfgouche())){
                infoList.add("是否购车 "+otherMsgBean.getMemberInfo().getSfgouche());
            }
            if(!StringUtil.isEmpty(otherMsgBean.getMemberInfo().getShouru())){
                infoList.add("年收入 "+otherMsgBean.getMemberInfo().getShouru());
            }


//            android.view.ViewGroup.LayoutParams lp = new android.view.ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
//            baseInfo.setPadding(30, 0, 30, 0);
            baseInfo.setOrientation(FlowLayout.HORIZONTAL);
            baseInfo.setHorizontalSpacing(40);
            baseInfo.setVerticalSpacing(30);
//            baseInfo.setLayoutParams(lp);
            baseInfo.removeAllViews();
            for(int i=0;i<infoList.size();i++){
                TextView tv = createTextView(infoList.get(i));
                baseInfo.addView(tv);
            }


            if (!baseBean.getData().getDongTaiList().isEmpty()) {
                mDtImgList = baseBean.getData().getDongTaiList();
                if (mDtImgList.size() == 4) {
                    mDtImgList.remove(3);
                }
                mDTImgAdapter.setNewData(mDtImgList);
            }
            if (!baseBean.getData().getWishList().isEmpty()) {
                mWishImgList = baseBean.getData().getWishList();
                if (mWishImgList.size() == 4) {
                    mWishImgList.remove(3);
                }
                mWishImgAdapter.setNewData(mWishImgList);
            }
            if(baseBean.getData().getLiWuList() != null && baseBean.getData().getLiWuList().size() > 0){
                mLwList = baseBean.getData().getLiWuList();
                mLiWuAdapter.setNewData(mLwList);
                rv_liwu.setVisibility(View.VISIBLE);
                noData.setVisibility(View.GONE);
            }else{
                rv_liwu.setVisibility(View.GONE);
                noData.setVisibility(View.VISIBLE);
            }
            if (baseBean.getData().getCanJiaSu() == 1) {
                tvFast.setVisibility(View.INVISIBLE);
            } else {
                tvFast.setVisibility(View.VISIBLE);
            }
            if (baseBean.getData().getSfgz() == 1) {
                tvCollOther.setText("已关注");
                tvCollOther.setTextColor(Color.parseColor("#FFAC1F"));
                gz_image.setImageResource(R.mipmap.ic_gz_select);
            } else {
                tvCollOther.setText("关注");
                tvCollOther.setTextColor(Color.parseColor("#777777"));
                gz_image.setImageResource(R.mipmap.ic_gz_unselect);
            }

            if(otherMsgBean.getSfdc() == 0){
                tvSayHello.setBackgroundResource(R.drawable.btn_orange_shape);
            }else{
                tvSayHello.setBackgroundResource(R.drawable.btn_gray_20_shape);
            }

//            fensi_bg.setText(otherMsgBean.getFsNumber()+"粉丝");
//            tv_dt_age.setText(otherMsgBean.getMemberInfo().getAge()+"");
//            tvMeName.setText(otherMsgBean.getMemberInfo().getNcName());
//            tvId.setText("用户ID："+otherMsgBean.getMemberInfo().getUserCode());
//            tvCity.setText("城市：" + otherMsgBean.getMemberInfo().getCity());
//            tvImotion.setText("情感状态：" + otherMsgBean.getMemberInfo().getQinggan());
//            tvTall.setText("身高：" + otherMsgBean.getMemberInfo().getShengao());
//            tvXl.setText("学历：" + otherMsgBean.getMemberInfo().getXueli());
////            tvSex.setText("性别：" + otherMsgBean.getMemberInfo().getSex());
//            tvWork.setText("职业：" + otherMsgBean.getMemberInfo().getZhiye());
//
//            if (otherMsgBean.getMemberInfo().getRzStatus().equals("1")) {
//                tvRealVerify.setVisibility(View.VISIBLE);
//            } else {
//                tvRealVerify.setVisibility(View.GONE);
//            }
//            if("男".equals(otherMsgBean.getMemberInfo().getSex())){
//                sex_logo.setImageResource(R.mipmap.man);
//                sex_bg.setBackgroundResource(R.drawable.btn_sex_man);
//            }else{
//                sex_logo.setImageResource(R.mipmap.woman);
//                sex_bg.setBackgroundResource(R.drawable.btn_sex_woman);
//            }
//            if ("是".equals(otherMsgBean.getMemberInfo().getMemberLevel())) {
//                vip_bg.setVisibility(View.VISIBLE);
//                vip_bg.setText("VIP");
//            } else {
//                vip_bg.setVisibility(View.GONE);
//            }
//
//            if(otherMsgBean.getSfdc() == 0){
//                tvSayHello.setBackgroundResource(R.drawable.btn_orange_shape);
//            }else{
//                tvSayHello.setBackgroundResource(R.drawable.btn_gray_20_shape);
//            }
//
//            if ("是".equals(otherMsgBean.getMemberInfo().getSuperVip())) {
//                vip_super_bg.setVisibility(View.VISIBLE);
//                vip_super_bg.setText("SVIP");
//            } else {
//                vip_super_bg.setVisibility(View.GONE);
//            }
//
//            RequestOptions options = new RequestOptions().fitCenter()
//                    .transform(new GlideBlurTransformation(this));
////            Glide.with(this).load(otherMsgBean.getMemberInfo().getHeadPic()).apply(options).into(new SimpleTarget<Drawable>() {
////                @Override
////                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
////                    ivBg.setImageDrawable(resource);
////                }
////            });
//            Glide.with(this).load(otherMsgBean.getMemberInfo().getHeadPic()).into(ivBg);
//            tvWishMoney.setText(otherMsgBean.getWishMoney());
//            tvHeartMsg.setText(otherMsgBean.getMemberInfo().getSignInfo());
////            tvId.setText(otherMsgBean.getMemberInfo().getId());
            fensi_bg.setText(otherMsgBean.getFsNumber() + "粉丝");
            tv_dt_age.setText(otherMsgBean.getMemberInfo().getAge() + "");
            tvMeName.setText(otherMsgBean.getMemberInfo().getNcName());
            tvId.setText("ID：" + otherMsgBean.getMemberInfo().getUserCode());
            if (otherMsgBean.getMemberInfo().getRzStatus().equals("1")) {
                tvRealVerify.setVisibility(View.VISIBLE);
            } else {
                tvRealVerify.setVisibility(View.GONE);
            }
            if ("男".equals(otherMsgBean.getMemberInfo().getSex())) {
                sex_logo.setImageResource(R.mipmap.man);
                sex_bg.setBackgroundResource(R.drawable.btn_sex_man);
            } else {
                sex_logo.setImageResource(R.mipmap.woman);
                sex_bg.setBackgroundResource(R.drawable.btn_sex_woman);
            }
            if ("是".equals(otherMsgBean.getMemberInfo().getMemberLevel())) {
                vip_bg.setVisibility(View.VISIBLE);
                vip_bg.setText("VIP");
            } else {
                vip_bg.setVisibility(View.GONE);
            }

            if ("是".equals(otherMsgBean.getMemberInfo().getSuperVip())) {
                vip_super_bg.setVisibility(View.VISIBLE);
                vip_super_bg.setText("SVIP");
            } else {
                vip_super_bg.setVisibility(View.GONE);
            }
            if (StringUtils.isEmpty(otherMsgBean.getMemberInfo().getHeadPic())) {
                ivBg.setImageResource(R.drawable.nim_avatar_default);
            } else {
                Glide.with(this).load(otherMsgBean.getMemberInfo().getHeadPic()).into(ivBg);
            }
            tvHeartMsg.setText(otherMsgBean.getMemberInfo().getSignInfo());
        };
        OtherModel otherModel = new OtherModel();//登录上传参数
        otherModel.setMemberId(SharedHelper.readId(this));
        otherModel.setOtherMemberId(mOtherMemberId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(otherModel));
        HttpMethods.getInstance().getOtherMemberInfo(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    /**
     * 生成商品属性的textView
     * @return
     */
    private TextView createTextView(final String info) {
        ViewGroup.LayoutParams tvlp = new ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
//        tvlp.setMargins(30, 0, 30, 20);
        final TextView tv = new TextView(this);
        tv.setPadding(30, 10, 30, 10);
        tv.setTextColor(getResources().getColor(R.color.color_333333));
        tv.setBackgroundResource(R.drawable.btn_gray_20_shape);
        tv.setTextSize(12f);
        tv.setText(info);
        tv.setLayoutParams(tvlp);
        return tv;
    }

    @OnClick({R.id.iv_back, R.id.dtRelation, R.id.wishRelation, R.id.tv_say_hello, R.id.talk_linear, R.id.gz_linear, R.id.tv_fast})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.dtRelation:
                bundle.putString("id", mOtherMemberId);
                bundle.putString("name",otherMsgBean.getMemberInfo().getNcName());
                RxActivityTool.skipActivity(this, DongTaiAndVideoActivity.class, bundle);
                break;
            case R.id.wishRelation:
                bundle.putString("id", mOtherMemberId);
                bundle.putString("name",otherMsgBean.getMemberInfo().getNcName());
                bundle.putInt("canJiaSu",otherMsgBean.getCanJiaSu());
                RxActivityTool.skipActivity(this, OtherWishActivity.class, bundle);
                break;
            case R.id.tv_say_hello:
                if (otherMsgBean.getSfdc() == 0) {
                    httpSayHello();
                }
                break;
            case R.id.talk_linear:
                if (SharedHelper.readId(this).equals(mOtherMemberId)) {
                    RxToast.normal("不能给自己发私信");
                } else {
                    NimUIKit.startP2PSession(this, mOtherMemberId);
                }

                break;
            case R.id.gz_linear:
                if (SharedHelper.readId(this).equals(mOtherMemberId)) {
                    RxToast.normal("不能关注自己");
                } else {
                    httpGz();
                }
                break;
            case R.id.tv_fast:
                if(otherMsgBean.getCanJiaSu() != 1){
                    httpCallFriends();
                }
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private void httpCallFriends() {

        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("加速成功");
            otherMsgBean.setCanJiaSu(1);
            tvFast.setVisibility(View.INVISIBLE);
        };
        OtherModel otherModel = new OtherModel();
        otherModel.setMemberId(SharedHelper.readId(this));
        otherModel.setOtherMemberId(mOtherMemberId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(otherModel));
        HttpMethods.getInstance().fridJiaSu(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    public void sendBroadcastToMain() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        //打招呼
        intent.setAction(MainActivity.UPDATE_DACALL);
        bundle.putString("memberId", mOtherMemberId);
        bundle.putInt("sfdc", 1);

        intent.putExtras(bundle);
        sendBroadcast(intent);
    }

    private void httpSayHello() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal(baseBean.getMsg());
            if(baseBean.isSuccess()){



                sendBroadcastToMain();
                tvSayHello.setBackgroundResource(R.drawable.btn_gray_shape);
            }else{
                if(baseBean.getMsg().contains("您今天的打招呼次数已经用完！")){
                    tvSayHello.setBackgroundResource(R.drawable.btn_gray_20_shape);
                }else if(baseBean.getMsg().contains("您今天已经给Ta打过招呼啦！")){
                    tvSayHello.setBackgroundResource(R.drawable.btn_gray_20_shape);
                }
            }
        };
        SayModel userModel = new SayModel();
        userModel.setMemberId(SharedHelper.readId(this));
        userModel.setOtherMemberId(mOtherMemberId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().callMember(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    private void httpGz() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal(baseBean.getMsg());
            if (tvCollOther.getText().toString().equals("已关注")) {
                tvCollOther.setText("关注");
                tvCollOther.setTextColor(Color.parseColor("#777777"));
                gz_image.setImageResource(R.mipmap.ic_gz_unselect);
            } else {
                tvCollOther.setText("已关注");
                tvCollOther.setTextColor(Color.parseColor("#FFAC1F"));
                gz_image.setImageResource(R.mipmap.ic_gz_select);
            }
        };
        GzModel userModel = new GzModel();
        userModel.setGzrId(SharedHelper.readId(this));
        userModel.setBgzId(mOtherMemberId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().saveGuanZhu(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }
}
